<template>
  <div class="container">
    <div class="main">
      <div class="main_content">
        <div class="main_header">
          <a-input
            placeholder="搜索学校名称"
            style="width: 160px; height: 36px"
            v-model="searchDetail"
          />
          <a-button
            type="primary"
            style="margin-left: 10px; width: 70px; height: 36px"
            @click="toSearch"
            :disabled="!isAuth(['ROOT', 'SCHOOL:SELECT'])"
          >
            查询
          </a-button>
          <a-button
            type="primary"
            style="margin-left: 10px; width: 70px; height: 36px"
            @click="toAdd"
            v-if="isAuth(['ROOT', 'SCHOOL:INSERT'])"
          >
            新增
          </a-button>
          <a-popconfirm
            :disabled="!isAuth(['ROOT', 'SCHOOL:DELETE'])"
            title="是否进行批量删除"
            ok-text="确认"
            cancel-text="取消"
            @confirm="confirm2"
            @cancel="cancel2"
          >
            <a-button
              v-if="isAuth(['ROOT', 'SCHOOL:DELETE'])"
              type="danger"
              style="margin-left: 10px; width: 98px; height: 36px"
            >
              批量删除
            </a-button>
          </a-popconfirm>
        </div>

        <div class="main_table">
          <!-- data-source 数据源,column 列名  row-selection列表项是否可选择	-->
          <!-- rowSelection 是计算属性进行加工处理 -->

          <a-spin
            size="large"
            v-show="loadingVisible"
            style="loading_icon"
            tip="正在加载中"
          ></a-spin>
          <!-- 务必使用 rowKey 来指定数据列的主键 我每一列的数据是 指定字段为id  那么我的值就会是id -->
          <a-table
            rowKey="id"
            :row-selection="{
              selectedRowKeys: selectedRowKeys,
              onChange: onSelectChange,
            }"
            :columns="columns"
            :data-source="data"
            :pagination="pagination"
            @change="handleTableChange"
          >
            <!-- 作用域插槽 text 本身是每一列的所有属性 但是 column的配置是 dataIndex 是avaurl 所以text 就变成了每一类的avarurl -->
            <span slot="action" slot-scope="text, record">
              <a
                @click="modifyItem(record)"
                v-if="isAuth(['ROOT', 'SCHOOL:UPDATE'])"
                >修改</a
              >
              <a-divider
                type="vertical"
                v-if="isAuth(['ROOT', 'SCHOOL:UPDATE'])"
              />
              <a-popconfirm
                :disabled="!isAuth(['ROOT', 'SCHOOL:DELETE'])"
                title="请确定是否删除该学校信息"
                ok-text="确定"
                cancel-text="取消"
                @confirm="deleteItem(record)"
                @cancel="cancel(record)"
              >
                <a
                  href="#"
                  :class="record.depts != '0' ? 'disableColor' : ''"
                  v-if="isAuth(['ROOT', 'SCHOOL:DELETE'])"
                >
                  删除
                </a>
              </a-popconfirm>
            </span>
          </a-table>
        </div>
      </div>
    </div>
    <add-or-update
      v-if="addOrUpdateVisible"
      ref="addOrUpdate"
      @refreshDataList="getRoleMessage"
    ></add-or-update>
  </div>
</template>
<script>
import AddOrUpdate from "../components/school-add-or-update.vue";
export default {
  components: {
    AddOrUpdate,
  },
  data() {
    return {
      selectedRowKeys: [], // Check here to configure the default column
      //
      loadingVisible: true,
      // 多选删除的表格信息
      idList: [],
      // 搜索框内容
      searchDetail: "",
      // 静态模态的出现
      addOrUpdateVisible: false,
      // 列名
      columns: [
        // title:列名; dataIndex: 对应数据源中的键值(kay)
        {
          title: "学校名称",
          dataIndex: "name",
        },

        {
          title: "系部数量",
          dataIndex: "depts",
        },
        {
          title: "操作",
          key: "action",
          scopedSlots: { customRender: "action" },
        },
      ],
      // 数据源
      data: [
        //  键值key 对应列名, key为Vue 需要key 可以忽略
      ],
      pagination: {
        defaultPageSize: 5,
        position: "bottom",
        pageSize: 10,
        pageSizeOptions: ["10", "15", "20", "25"],
        current: 1,
        total: 0,
        showTotal: (total, range) => {
          return range[0] + "-" + range[1] + " 共" + total + "条";
        },
        showQuickJumper: true,
        showSizeChanger: true,
      },
      //   表头的配置条件
      sortedInfo: null,
    };
  },
  created() {
    // this.getRoleMessage();
    // 分页查询数据
    this.searchRole();
    // this.getUserMessage();
  },
  methods: {
    onSelectChange(selectedRowKeys) {
      console.log("selectedRowKeys changed:123 ", selectedRowKeys);
      this.selectedRowKeys = selectedRowKeys;
      let ids = [];
      selectedRowKeys.forEach((item) => {
        ids.push(item);
      });
      this.idList = ids;
    },
    // 批量删除按钮 确认弹框
    confirm2(e) {
      this.mutiDelete();
    },
    // 批量删除按钮 取消弹框
    cancel2() {},
    // 批量删除
    async mutiDelete() {
      console.log(this.idList);
      this.loadingVisible = true;
      const { data: res } = await this.$http.delete("/admin/schools", {
        data: {
          ids: this.idList,
        },
      });
      if (res.code == 200) {
        this.common.notify("success", "删除成功");
        // 将删除的元素 从selectedRowKeys中过滤出去
        this.idList.forEach((target) => {
          this.selectedRowKeys = this.selectedRowKeys.filter((item) => {
            return item != target;
          });
        });
        this.pagination.current = 1;
        console.log("删除后", this.selectedRowKeys);
        this.getRoleMessage();
      } else {
        this.loadingVisible = false;
        this.common.notify("warning", "无法删除,请重新选择");
      }
    },
    modifyItem(record) {
      this.loadingVisible = true;
      this.addOrUpdateVisible = true;
      this.$nextTick(() => {
        this.$refs.addOrUpdate.update(record);
      });
    },

    // 查询用户
    async toSearch() {
      this.loadingVisible = true;
      if (this.searchDetail == "") {
        this.getRoleMessage();
      } else {
        const { data: res } = await this.$http.get(
          `/admin/schools?name=${this.searchDetail}`
        );
        this.loadingVisible = false;
        this.data = res.data.records;
      }
    },
    toAdd() {
      this.loadingVisible = true;
      this.addOrUpdateVisible = true;
      this.$nextTick(() => {
        this.$refs.addOrUpdate.init();
        // 清空表单 发送请求 获取表单项的部分选择数据.
      });
    },
    async deleteItem(item) {
      this.loadingVisible = true;
      // 只有系部为0 才能够进行删除
      if (item.depts == 0) {
        let ids = [item.id];
        const { data: res } = await this.$http.delete("/admin/schools", {
          data: {
            ids: ids,
          },
        });
        if (res.code == 200) {
          // 若我已经选中了这个元素 然后再点击删除 那么我的rowkeys 会记录这keys值 但是实际上这个元素已经被我删掉了
          // 所以也要进行以遍历  将selectedRowKeys中与删除的这个id 相同的元素也要去掉
          this.selectedRowKeys = this.selectedRowKeys.filter((target) => {
            return target != item.id;
          });
          // 删除后 重定向到第一页
          this.pagination.current = 1;
          this.common.notify("success", "删除成功");
          this.getRoleMessage();
        }
      } else {
        this.loadingVisible = false;
        // this.$message.warning("无法删除");
        this.common.notify("warning", "无法删除");
      }
    },
    // 分页点击切换
    handleTableChange(pagination, filters, sorter) {
      this.pagination.current = pagination.current;
      this.pagination.pageSize = pagination.pageSize;
      let that = this;
      that.sortedInfo = sorter;
      const pager = { ...that.pagination };
      pager.current = pagination.current;
      that.pagination = pager;
      this.searchRole();
    },

    // 分页查询
    async getRoleMessage(val) {
      this.searchRole();
    },
    // 分页查询显示
    async searchRole() {
      //  `/admin/schools?page=${this.pagination.current}&size=${this.pagination.pageSize}`
      const { data: res } = await this.$http.get(
        `/admin/schools?page=${this.pagination.current}&size=${this.pagination.pageSize}`
      );
      this.loadingVisible = false;
      //   必须要是 数字型的
      this.pagination.total = Number(res.data.total);
      this.data = res.data.records;
    },
  },
  computed: {},
};
</script>
<style  lang='less' scoped>
.container {
  box-sizing: border-box;
  display: flex;
  background-color: #eef1f2;
  // overflow: scroll;
  padding: 35px 75px;

  .main {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-items: center;
    // overflow: scroll;
    background-color: #eef1f2;
    // box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
    .main_content {
      padding: 20px;
      padding-top: 20px;
      width: 100%;
      height: 100%;
      background-color: #fff;
      border-radius: 10px;
      .main_header {
        display: flex;
        margin-bottom: 25px;
        .main_table {
          margin-top: 50px;
        }
      }
    }
  }
}
/deep/ .ant-table-thead > tr > th,
.ant-table-tbody > tr > td {
  text-align: center;
}
/deep/ .ant-table-tbody > tr > td {
  text-align: center !important;
}

.disableColor {
  color: #eee;
}
.loading_icon {
  position: absolute;
}
/deep/ .ant-spin-spinning {
  z-index: 100;
  position: absolute;
  top: 50%;
  left: 55%;
}
</style>